package net.wangds.crypt.aes.utils;

import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2020/10/19 18:50.
 */
public class AbstractAesUtils {

    protected static final String ALGORITHM = "AES";

    /**
     * 密码分组链接模式（Cipher Block Chaining (CBC)
     */
    protected static final String MOD_CBC = "CBC";
    /**
     * 电码本模式（Electronic Codebook Book (ECB)）.
     */
    protected static final String MOD_ECB = "ECB";
    /**
     * 计算器模式（Counter (CTR)）.
     */
    protected static final String MOD_CTR = "CTR";
    /**
     * 输出反馈模式（Output FeedBack (OFB)）.
     */
    protected static final String MOD_OCF = "OCF";
    /**
     * 密码反馈模式（Cipher FeedBack (CFB)）.
     */
    protected static final String MOD_CFB = "CFB";

    protected static final String PADDING_PKCS5 = "PKCS5Padding";
    protected static final String PADDING_PKCS7 = "PKCS7Padding";
    protected static final String PADDING_NO = "NoPadding";

    protected static final int LEN_128 = 128;
    protected static final int LEN_256 = 256;

    static {
        Security.addProvider(new BouncyCastleProvider());
    }


    protected static void checkKey(String sKey, int keyLength){
        if(StringUtils.isBlank(sKey)){
            throw new NullPointerException("AES密钥不能是空字符串");
        }
        // 判断Key是否为16位
        if (sKey.length() != keyLength/8) {
            throw new IndexOutOfBoundsException("AES密钥长度不足"+keyLength+"位");
        }
    }

    public static byte[] encrypt(byte[] bsSrc, String sKey, String sVi, int keyLength, String mod, String padding) {
        try {
            checkKey(sKey, keyLength);

            byte[] raw = sKey.getBytes(StandardCharsets.ISO_8859_1);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", ALGORITHM, mod, padding),"BC");//"算法/模式/补码方式"
            IvParameterSpec iv = new IvParameterSpec(sVi.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            return cipher.doFinal(bsSrc);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] decrypt(byte[] sSrc, String sKey, String sVi, int keyLength, String mod, String padding) {
        try {
            checkKey(sKey, keyLength);
            byte[] raw = sKey.getBytes(StandardCharsets.ISO_8859_1);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s",  ALGORITHM, mod, padding), "BC");
            IvParameterSpec iv = new IvParameterSpec(sVi.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            try {
                return cipher.doFinal(sSrc);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


}
